package com.example.displayorientation.slice;

import com.example.displayorientation.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.AbilityInfo;

public class MainAbilitySlice extends AbilitySlice {

    // 是否固定屏幕方向
    private boolean isOrientationFixed = true;


    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        Text txToHorizontal = (Text) findComponentById(ResourceTable.Id_text_to_horizontal);
        txToHorizontal.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                // 将屏幕方向强制改变为横向
                setDisplayOrientation(AbilityInfo.DisplayOrientation.LANDSCAPE);

            }
        });

        Text txToVertical = (Text) findComponentById(ResourceTable.Id_text_to_vertical);
        txToVertical.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                // 将屏幕方向强制改变为纵向
                setDisplayOrientation(AbilityInfo.DisplayOrientation.PORTRAIT);

            }
        });


        Text txFixedVertical = (Text) findComponentById(ResourceTable.Id_text_fixed_vertical);
        txFixedVertical.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                isOrientationFixed = !isOrientationFixed;
                new ToastDialog(MainAbilitySlice.this).setText("固定屏幕方向:" + isOrientationFixed).show();
            }
        });
    }

    // 复写setDisplayOrientation方法
    @Override
    public void setDisplayOrientation(AbilityInfo.DisplayOrientation requestedOrientation) {
        // 当isOrientationFixed为true时保持纵向(或横向)屏幕方向
        if (isOrientationFixed) {
            super.setDisplayOrientation(AbilityInfo.DisplayOrientation.PORTRAIT);
            return;
        }
        super.setDisplayOrientation(requestedOrientation);
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
